<template>
  <view class="box-bg">
    <uni-nav-bar shadow color="#F7F7F7" left-icon="left" backgroundColor="#3485FD" height="65px" title="就近加油"
      @clickLeft="back" />
  </view>
  <view class="xiaoxi">
    <view class="top">
      <view class="top1">
        <input type="text" v-model="inputValue" class="input_model" placeholder="请输入加油站名字">
        <image src="/static/lsh_0202.png" class="search_icon"></image>
        <view class="icon_container">
          <image src="/static/lsh_0203.png" class="icon_change_style"></image>
          <view class="text_container" @click="listStation">
            <view class="top_text">列表</view>
            <view class="bottom_text">模式</view>
          </view>
        </view>
      </view>
      <view class="card">
        <map :latitude="latitude" :longitude="longitude" :markers="markers" :polyline="polyline" :controls="controls"
          :include-points="includePoints" :show-location="true" :show-scale="true" :enable-3d="true"
          :enable-overlooking="true" :enable-rotate="true" :enable-scroll-geometry="true" @markertap="handleMarkerTap"
          style="height: 100%;"></map>
      </view>

      <!-- 改为动态显示选中的加油站信息 -->
      <view class="daohang" v-if="selectedStation">
        <view class="jiayouzhan">
          <view class="jiayouzhan-1">
            <view class="jiayouzhan-1-1">{{ selectedStation.title }}</view>
            <view class="jiayouzhan-1-2">{{ selectedStation.address }}</view>
            <view class="jiayouzhan-1-3" @click="stationdetil">
              <uni-icons type="info" color="#3486fd" size="15"></uni-icons>
              <text>门店详情>></text>
            </view>
          </view>
          <view class="img">
            <image :src="selectedStation.img" style="width: 200rpx; height: 140rpx; border-radius: 20rpx"></image>
          </view>
        </view>
        <view class="daohang-1">
          <view class="daohang-1-1">立即导航</view>
        </view>
      </view>
      <view class="daohang" v-else>
        <view class="jiayouzhan-1-2-1">请点击地图上的加油站标记查看详情</view>
        <view class="jiayouzhan-1-2-2">暂未选择</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import baseUrl from '@/untils/urlConfig';
import unirequest from '@/untils/unirequest';
import { onLoad } from '@dcloudio/uni-app'

// 定义响应式数据
const allNearbyStations = ref([]);
const inputValue = ref('')
const markers = ref([])  // 修正：直接使用markers变量
const polyline = ref([])
const controls = ref([])
const includePoints = ref([])
const latitude = ref(34.826135)  // 新增：地图中心经纬度
const longitude = ref(113.558813)
const userMarker = ref({  // 新增：用户位置标记
  id: -1,
  latitude: 0,
  longitude: 0,
  width: 20,
  height: 25,
  iconPath: '../../static/user_location.png'  // 建议替换为实际用户定位图标路径
})
const selectedStation = ref(null)  // 新增：记录选中的加油站


const getUserLocation = async () => {
  try {
    const { latitude: currentLat, longitude: currentLng } = await uni.getLocation({ type: 'wgs84' });
    // 关键修改：将获取到的经纬度同步到地图中心变量
    latitude.value = currentLat;
    longitude.value = currentLng;
    userMarker.value.latitude = currentLat;
    userMarker.value.longitude = currentLng;
    // 将用户位置标记合并到mks数组（确保不重复）
    const isUserMarkerExist = markers.value.some(marker => marker.id === -1);
    if (!isUserMarkerExist) {
      markers.value.unshift(userMarker.value);  // 添加到数组最前面（避免被加油站图标覆盖）
    }
    return { userLat: currentLat, userLng: currentLng };
  } catch (error) {
    uni.showToast({
      title: '获取位置失败，请开启定位权限',
      icon: 'none'
    });
    return null;
  }
};
const getDistance = (lat1, lng1, lat2, lng2) => {
  const R = 6371; // 地球半径（Km）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLng = (lng2 - lng1) * Math.PI / 180;
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLng / 2) * Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return parseFloat((R * c).toFixed(2)); // 保留两位小数
};
const getStationList = async () => {
  try {
    // 先获取用户位置
    uni.showLoading({ title: '加载中...' });
    const userLocation = await getUserLocation();
    if (!userLocation) {
      uni.hideLoading();  // 位置获取失败时隐藏
      console.log("⚠️ 用户位置获取失败，未授权或设备不支持");
      return;
    }
    // 获取用户经纬度

    console.log("✅ 用户位置获取成功，经纬度：", userLocation.userLat, userLocation.userLng); // 打印用户位置
    const res = await unirequest({
      url: `${baseUrl}/gas/station/list`,
      method: 'GET'
    });
    console.log("接口返回原始数据：", res.data); // 打印接口原始响应
    if (res.data.code === 200) {
      // 筛选距离小于1km的加油站
      const filteredStations = res.data.rows.filter(station => {
        const distance = getDistance(
          userLocation.userLat,
          userLocation.userLng,
          Number(station.latitude),  // 字符串转数值
          Number(station.longitude)
        );
        return distance < 1; // 只保留距离小于1km的
      });
      allNearbyStations.value = filteredStations;
      updateMarkersBasedOnSearch();
      console.log("筛选后符合条件的加油站数量：", filteredStations.length);
    } else {
      console.log("⚠️ 接口返回非200状态码，错误信息：", res.data.msg);
    }
    uni.hideLoading();  // 隐藏加载
  } catch (error) {
    console.error("❌ 获取加油站列表异常：", error);
    uni.hideLoading();
  }
};
const updateMarkersBasedOnSearch = () => {
  const keyword = inputValue.value.trim().toLowerCase();

  // 筛选逻辑：同时满足距离条件和关键字匹配（名称或地址包含关键字）
  const filteredStations = allNearbyStations.value.filter(station => {
    const name = station.name.toLowerCase();
    const address = station.address.toLowerCase();
    return keyword ? (name.includes(keyword) || address.includes(keyword)) : true;
  });
  // 生成标记（匹配关键字的使用不同图标）
  const stationMarkers = filteredStations.map(station => ({
    id: station.id,
    latitude: Number(station.latitude),
    longitude: Number(station.longitude),
    width: 20,
    height: 25,
    // 关键修改：根据是否匹配关键字切换图标
    iconPath: keyword ?
      (station.name.toLowerCase().includes(keyword) || station.address.toLowerCase().includes(keyword)) ?
        '../../static/dw.png' : '../../static/dw1.png' :
      '../../static/dw1.png',
    title: station.name,
    address: station.address,
    phone: station.phone,
    week: station.week,
    img: station.img
  }));

  // 更新地图标记（保留用户位置）
  markers.value = [userMarker.value, ...stationMarkers];
};

// 新增：监听搜索框输入变化
watch(inputValue, () => {
  updateMarkersBasedOnSearch();
}, { immediate: true }); // 初始加载时执行一次
// 新增：标记点击处理函数
const handleMarkerTap = (e) => {
  const markerId = e.detail.markerId;
  // 排除用户自己的标记（id=-1）
  if (markerId === -1) return;
  // 查找对应的加油站数据
  const station = markers.value.find(marker => marker.id === markerId);
  // 关键修改：判断是否点击的是当前已选中的标记
  if (selectedStation.value?.id === markerId) {
    selectedStation.value = null;  // 再次点击时隐藏信息框
  } else {
    selectedStation.value = station;  // 首次点击时显示信息
  }
};
const stationdetil = () => {
  const stationId = selectedStation.value.id;  // 获取选中的加油站ID
  uni.navigateTo({
    url: `/pages/jiayouzhan/jiayouzhan?id=${stationId}`  // 传递加油站ID
  });
}
// 返回上一页方法
const back = () => {
  uni.navigateBack()
}
const listStation = () => {
  uni.navigateTo({
    url: '/pages/lsh_nearby_refeling_list/lsh_nearby_refeling_list'
  })
}
onLoad(() => {
  getStationList(); // 页面加载时获取加油站列表
});
</script>

<style scoped>
.box-bg {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 1000;
}

.top1 {
  display: flex;
  position: relative;
  top: 40rpx;
  right: 15rpx;
}

.input_model {
  margin-left: 5%;
  width: 75%;
  height: 40px;
  margin-top: 36rpx;
  position: relative;
  padding: 0 80rpx 0 30rpx;
  /* 右侧留出图标空间 */
  border: 1px solid #d3d3d3;
  border-radius: 25px;
  background-color: white;
}

.search_icon {
  position: absolute;
  /* 修正拼写 */
  right: 200rpx;
  /* 替换 margin-left */
  width: 40rpx;
  /* 必须指定尺寸 */
  height: 40rpx;
  top: 52rpx;
}

.icon_container {
  position: relative;
  display: flex;
}

.text_container {
  position: absolute;
  color: white;
  top: 25rpx;
  left: 70rpx;
}


.icon_change_style {
  height: 140rpx;
  width: 140rpx;
  margin-left: 35rpx;
}

.top_bottom {
  height: 200rpx;
}

.top_text,
.bottom_text {
  margin-left: 7rpx;
  font-weight: 600;
}

.bottom_text {
  margin-top: 6rpx;
}

.xiaoxi {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: #f7f7f7;
  top: 116rpx
}

.top {
  width: 100%;
  height: 400rpx;
  background-color: rgb(52, 134, 253);
  background-size: cover;
}

.title {
  width: 100%;
  color: white;
  text-align: center;
  padding: 30rpx 0;
  font-size: 35rpx;
}

.card {
  border-radius: 20rpx;
  height: 850rpx;
  position: relative;
  top: 80rpx;
  width: 96%;
  margin-left: 2%;
  background-color: white
}

.card map {
  width: 96%;
  height: 800rpx;
  margin-left: 2%;
  position: relative;
  top: 25rpx
}

.search {
  width: 88%;
  margin: 20rpx auto 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ditumoshi {
  margin-left: 20rpx;
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #ff4000;
  color: white;
  font-size: 24rpx;
  text-align: center;
}

.text {
  width: 60rpx;
  height: 60rpx;
  margin: 10rpx auto 0;
}

.img {
  width: 200rpx;
  height: 140rpx;
  border-radius: 20rpx;
  margin-right: 20rpx;
}

.daohang {
  background-color: white;
  border-radius: 20rpx;
  position: relative;
  height: 300rpx;
  width: 96%;
  margin-left: 2%;
}

.daohang-1 {
  width: 90%;
  margin-left: 5%;
  display: flex;
  align-items: center;
  background-color: #0662E6;
  height: 60rpx;
  border-radius: 30rpx;
  justify-content: center;
  margin-top: 30rpx;
}

.daohang-1-1 {
  font-size: 30rpx;
  color: white;
}

.jiayouzhan {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 20rpx 10rpx 34rpx;
}

.jiayouzhan-1 {
  width: 60%;
}

.jiayouzhan-1-1 {
  font-size: 30rpx;
  color: black;
  margin-bottom: 15rpx;
}

.jiayouzhan-1-2 {
  font-size: 24rpx;
  color: #999;

}

.jiayouzhan-1-2-1 {
  font-size: 24rpx;
  color: #999;
  margin-left: 24%;
}

.jiayouzhan-1-2-2 {
  font-size: 40rpx;
  color: #999;
  margin-left: 40%;
  margin-top: 86rpx;
}

.jiayouzhan-1-3 {
  font-size: 24rpx;
  color: #3486fd;
  display: flex;
  align-items: center;
  margin-top: 15rpx;
}
</style>